package com.ycb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ycb.common.Result;
import com.ycb.dto.DishDto;
import com.ycb.pojo.Category;
import com.ycb.pojo.Dish;
import com.ycb.mapper.DishMapper;
import com.ycb.pojo.DishFlavor;
import com.ycb.service.ICategoryService;
import com.ycb.service.IDishFlavorService;
import com.ycb.service.IDishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品管理 服务实现类
 * </p>
 *
 * @author ycb
 * @since 2024-09-30
 */
@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements IDishService {
    public static List<Category> CATEGORIES;
    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IDishFlavorService iDishFlavorService;

    @Override
    public long findCountByCategoryId(Long id) {
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
        dishQueryWrapper.eq(Dish::getCategoryId,id);
        return this.count(dishQueryWrapper);
    }

    @Override
    @Transactional
    public boolean saveWithFlavor(DishDto dishDto) {
        this.save(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();
        //保存风味表
        if (flavors == null || flavors.isEmpty()) {
            log.info("当前菜品不存在风味选择");
            return false;
        }
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        iDishFlavorService.saveBatch(flavors);
        return true;
    }

    @Override
    public DishDto getWithFlavorById(Long id) {
        Dish byId = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(byId,dishDto);
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,id);
        dishFlavorLambdaQueryWrapper.orderByAsc(DishFlavor::getCreateTime);
        List<DishFlavor> list = iDishFlavorService.list(dishFlavorLambdaQueryWrapper);
        dishDto.setFlavors(list);
        return dishDto;
    }

    @Override
    public boolean updateWithFlavor(DishDto dishDto) {
        //更新菜品信息
        this.updateById(dishDto);

        //更新风味信息
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        iDishFlavorService.remove(dishFlavorLambdaQueryWrapper);

        //保存修改的风味
        List<DishFlavor> flavors = dishDto.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            for (DishFlavor flavor : flavors) {
                flavor.setId(null);
                flavor.setDishId(dishDto.getId());
            }
            iDishFlavorService.saveBatch(flavors);
        }
        return true;
    }

    @Override
    public Result<Page> pageDishDto(int page, int pageSize, String name) {
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //构造条件构造器
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件（当我们没有输入name时，就相当于查询所有了）
        dishQueryWrapper.like(!(name == null || "".equals(name)), Dish::getName, name);
        //并对查询的结果进行降序排序，根据更新时间
        dishQueryWrapper.orderByDesc(Dish::getUpdateTime);
        this.page(dishPage,dishQueryWrapper);

        //复制dish的信息
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        List<Dish> records = dishPage.getRecords();
        List<DishDto> dishDtos = dish2dishDto(records,true,false);
        dishDtoPage.setRecords(dishDtos);
        return Result.success(dishDtoPage);
    }

    /**
     * dish 转换为dishDto
     * @param dishList
     * @return
     */
    public List<DishDto> dish2dishDto(List<Dish> dishList,Boolean needCategoryName,Boolean needDishFlavor){
        List<DishDto> dishDtos = new ArrayList<>();
        for (Dish record : dishList) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record,dishDto);
            dishDtos.add(dishDto);
        }
        if (needCategoryName) {
            //查询菜品分类信息
            if (CATEGORIES ==null || CATEGORIES.isEmpty()) {
                CATEGORIES = categoryService.listByType(1);
            }

            Map<Long, List<Category>> collect = CATEGORIES.stream().collect(Collectors.groupingBy(Category::getId));
            for (DishDto dishDto : dishDtos) {
                List<Category> categories = collect.get(dishDto.getCategoryId());
                if (categories != null && !categories.isEmpty()) {
                    dishDto.setCategoryName(categories.get(0).getName());
                }
            }
        }

        if (needDishFlavor) {
            List<Long> dishIds = dishList.stream().map(Dish::getId).collect(Collectors.toList());
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.in(DishFlavor::getDishId,dishIds);
            dishFlavorLambdaQueryWrapper.orderByAsc(DishFlavor::getCreateTime);
            List<DishFlavor> dishFlavorList = iDishFlavorService.list(dishFlavorLambdaQueryWrapper);
            Map<Long, List<DishFlavor>> dishFlavorMap = dishFlavorList.stream().collect(Collectors.groupingBy(DishFlavor::getDishId));
            for (DishDto dishDto : dishDtos) {
                List<DishFlavor> myFlavors = dishFlavorMap.get(dishDto.getId());
                if (myFlavors != null && !myFlavors.isEmpty()) {
                    dishDto.setFlavors(myFlavors);
                }
            }
        }
        return dishDtos;
    }

    @Override
    @Transactional
    public void removeWithFlavorByIds(List<Long> ids) {
        QueryWrapper<DishFlavor> dishFlavorQueryWrapper = new QueryWrapper<>();
        dishFlavorQueryWrapper.in("dish_id",ids);
        iDishFlavorService.remove(dishFlavorQueryWrapper);
        this.removeBatchByIds(ids);
    }

    @Override
    public Result<List<DishDto>> listByCategoryId(String categoryId) {
        //条件查询器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //根据传进来的categoryId查询
        queryWrapper.eq(categoryId != null, Dish::getCategoryId, categoryId);
        //只查询状态为1的菜品（在售菜品）
        queryWrapper.eq(Dish::getStatus, 1);
        //简单排下序，其实也没啥太大作用
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //获取查询到的结果作为返回值
        List<Dish> list = this.list(queryWrapper);
        log.info("查询到的菜品信息list:{}", list);
        //item就是list中的每一条数据，相当于遍历了
        List<DishDto> dishDtoList = dish2dishDto(list,false,true);
        return Result.success(dishDtoList);
    }
}
